package org.example.mallweb.mallservice.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.mallcommon.myenum.ActionType;
import org.example.mallcommon.projo.ScoreRule;
import org.example.mallweb.mallservice.mapperervice.taguservalue.TagUserScoreMapperImpl;
import org.example.mallweb.mallservice.service.TagUserValueService;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

import java.util.stream.Collectors;

/**
 * @author 韩先楚
 * 用户标签值服务接口
 */
@Service
public class TagUserValueServiceImpl implements TagUserValueService {

    @Resource
    private TagUserScoreMapperImpl tagUserScoreMapper;

    @Override
    public void addTagValue(Integer userId, List<Long> tagsIds, ActionType actionType) {
        //查找用户没有的标签并补上
        List<Long> tags = tagUserScoreMapper.list(new QueryWrapper<ScoreRule>().eq("user_id", userId)).stream().map(scoreRule -> scoreRule.getTagId()).collect(Collectors.toList());
        List<ScoreRule> list = tagsIds.stream()
                .filter(aLong -> !tags.contains(aLong))
                .map(new Function<Long, ScoreRule>() {
                    @Override
                    public ScoreRule apply(Long aLong) {
                        ScoreRule scoreRule = new ScoreRule();
                        scoreRule.setUserId(userId);
                        scoreRule.setTagId(aLong);
                        scoreRule.setCreateTime(new Date());
                        scoreRule.setUpdateTime(new Date());
                        return scoreRule;
                    }
                }).collect(Collectors.toList());
        if (list.size() > 0)
            tagUserScoreMapper.saveBatch(list);

        //更新标签值
        tagUserScoreMapper.update(new UpdateWrapper<ScoreRule>()
                .eq("user_id", userId)
                .in("tag_id", tagsIds)
                .setSql("score_value = score_value * 0.9+ " +actionType.getValue()));

    }


}
